Skip to content

The solution is to serialize head_dtype in `ImageClassifier.get_config()#2614

Closed
yashwanth510 wants to merge 4 commits intokeras-team:masterfrom
yashwanth510:fix/image-classifier-head-dtype-serialization
Closed

The solution is to serialize head_dtype in `ImageClassifier.get_config()#2614
yashwanth510 wants to merge 4 commits intokeras-team:masterfrom
yashwanth510:fix/image-classifier-head-dtype-serialization

Conversation

@yashwanth510
Copy link

Fix: Preserve head_dtype Across Save/Load

What’s the issue?

ImageClassifier.__init__() accepts a head_dtype argument and uses it to configure the dtype policy of the classifier head layers:

  • self.pooler
  • self.output_dropout
  • self.output_dense

However, head_dtype was never stored as an instance attribute and wasn’t included in get_config(). As a result, the value was silently dropped during model serialization.

This means that after saving and loading a model, the custom head_dtype would no longer be preserved.


Root Cause

In __init__():

head_dtype = head_dtype or backbone.dtype_policy

The value was used to configure layers, but:

  • It was never assigned to self.head_dtype
  • It was never returned in get_config()

So it never made it into the model config.

You can reproduce the issue like this:

model = keras_hub.models.ResNetImageClassifier(
    backbone=backbone,
    num_classes=10,
    head_dtype="float32",
)

print("head_dtype" in model.get_config())  # False

The Fix

Two small changes in image_classifier.py:

1. Store the value in __init__()

self.head_dtype = head_dtype

2. Include it in get_config()

"head_dtype": self.head_dtype,

Verification

model = keras_hub.models.ResNetImageClassifier(
    backbone=backbone,
    num_classes=10,
    head_dtype="float32",
)

model.compile()
model.save("/tmp/resnet_fixed.keras")

loaded = keras.models.load_model("/tmp/resnet_fixed.keras")

print("head_dtype in config:", "head_dtype" in model.get_config())
print("head_dtype before save:", model.head_dtype)
print("head_dtype after load:", loaded.head_dtype)
print("dtype preserved:", str(model.head_dtype) == str(loaded.head_dtype))

Expected behavior:

  • head_dtype appears in config
  • Value matches before and after loading
  • Dtype is preserved correctly

Impact

This affects all classifiers inheriting from ImageClassifier, including:

  • ResNetImageClassifier
  • EfficientNetImageClassifier
  • ViTImageClassifier
  • and other subclasses

Fixes #2085.

head_dtype was accepted by __init__() and used to set the dtype
policy for pooler, output_dropout, and output_dense layers,
but was never stored on self or included in get_config().
This caused head_dtype to be silently lost on save/load round-trips.

Fixes keras-team#2085
head_dtype was accepted by __init__() and used to set dtype policy
for pooler, output_dropout, and output_dense layers, but was never
stored on self or included in get_config(). This caused head_dtype
to be silently lost on save/load round-trips.

Fixes keras-team#2085
@gemini-code-assist
Copy link
Contributor

Summary of Changes

Hello @yashwanth510, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request resolves a critical issue where the head_dtype configuration for ImageClassifier models was not being preserved during serialization. Previously, custom dtype policies for the classifier head layers would be silently dropped when a model was saved and reloaded. The implemented solution ensures that the head_dtype is correctly stored as an instance attribute and included in the model's configuration, thereby maintaining the intended dtype policy throughout the model's lifecycle and preventing unexpected behavior after deserialization.

Highlights

  • Serialization Fix: The head_dtype argument, which configures the dtype policy of classifier head layers, was not being stored as an instance attribute or included in get_config(), leading to its loss during model serialization.
  • Preserved head_dtype: The fix ensures that the head_dtype is now stored as self.head_dtype in the __init__ method and is correctly serialized via the get_config() method, preserving its value across save/load operations.
  • Impacted Models: This change affects all classifiers inheriting from ImageClassifier, including ResNetImageClassifier, EfficientNetImageClassifier, and ViTImageClassifier, ensuring their head_dtype is consistently maintained.

🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console.

Changelog
  • keras_hub/src/models/image_classifier.py
    • Assigned the head_dtype parameter to self.head_dtype within the __init__ method to store it as an instance attribute.
    • Added self.head_dtype to the dictionary returned by the get_config method to ensure its serialization.
Activity
  • No human activity has been recorded on this pull request yet.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

@google-cla
Copy link

google-cla bot commented Feb 26, 2026

Thanks for your pull request! It looks like this may be your first contribution to a Google open source project. Before we can look at your pull request, you'll need to sign a Contributor License Agreement (CLA).

View this failed invocation of the CLA check for more information.

For the most up to date status, view the checks section at the bottom of the pull request.

Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request correctly addresses a serialization issue with head_dtype in the ImageClassifier by ensuring it's stored as an instance attribute and included in the model's configuration. The fix is well-implemented. My review includes minor suggestions to remove temporary comments added for the pull request's context, which will improve long-term code maintainability. While not part of the code changes, I'd also recommend adding an automated test case for model saving to verify this fix and prevent future regressions, as demonstrated in the PR description.

@yashwanth510
Copy link
Author

I have signed the CLA.

@yashwanth510
Copy link
Author

All of the local tests pass, including "test_head_dtype":

pytest keras_hub/src/models/resnet/ -v → 9 passed, 9 skipped ✅

The CI failures seem to be caused by tests that were already flaky and have nothing to do with this change (JAX GPU, nightly builds, etc.).
Could a maintainer run the failing checks again?

cc: @mattdangerw

yashwanth510 added a commit to yashwanth510/keras-hub that referenced this pull request Mar 2, 2026
head_dtype was accepted by __init__() and used to set dtype policy
for classifier head layers, but was never stored on self or included
in get_config() in several ImageClassifier subclasses.

Affected models:
- VitImageClassifier
- DeiTImageClassifier
- VGGImageClassifier
- MobileNetImageClassifier
- MobileNetV5ImageClassifier
- HGNetV2ImageClassifier

This is a follow-up to keras-team#2614 which fixed the same issue in the
base ImageClassifier class.
@yashwanth510
Copy link
Author

Closing in favour of #2617 which includes this fix
along with the same fix for all subclasses as
requested by @sachinprasadhs.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Downloaded model deserialization failure

1 participant